class WebsocketUtil {
  constructor(url, time) {
    this.url = url;
    this.time = time;
    this.is_open_socket = false;
    this.socketTask = null;
    this.heartbeatInterval = null;
    this.reconnectTimeOut = null;

    this.connectSocketInit();
  }

  connectSocketInit() {
    this.socketTask = uni.connectSocket({
      url: this.url,
      success: () => {
        console.log("WebSocket连接初始化...");
      },
      fail: (err) => {
        console.error("连接失败:", err);
        this.reconnect();
      }
    });

    this.socketTask.onOpen((res) => {
      console.log("WebSocket连接成功！");
      this.is_open_socket = true;
      clearTimeout(this.reconnectTimeOut);
      this.startHeartbeat();
      // 监听消息
      // this.socketTask.onMessage((res) => {
      //   console.log("收到消息:", res.data);
      // });
    });

    this.socketTask.onClose(() => {
      console.log("连接已关闭");
      this.is_open_socket = false;
      this.reconnect();
    });

    this.socketTask.onError((err) => {
      console.error("WebSocket错误:", err);
      this.is_open_socket = false;
      this.reconnect();
    });
  }

  send(data) {
    if (this.is_open_socket) {
      this.socketTask.send({
        data: JSON.stringify(data),
        success: () => {
          console.log("消息发送成功");
        },
        fail: (err) => {
          console.error("发送失败:", err);
          this.reconnect();
        }
      });
    } else {
      console.warn("连接未建立，消息暂存或重连");
      // 可选：将消息存入队列，连接恢复后发送
    }
  }

  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.is_open_socket) {
        const data = { value: "心跳检测", method: "heartbeat" };
        this.send(data);
      }
    }, this.time);
  }

  reconnect() {
    clearInterval(this.heartbeatInterval);
    if (!this.is_open_socket) {
      this.reconnectTimeOut = setTimeout(() => {
        console.log("尝试重连...");
        this.connectSocketInit();
      }, 3000);
    }
  }

  getMessage(callback) {
    if (this.socketTask) {
      this.socketTask.onMessage((res) => {
        callback(res.data);
      });
    }
  }

  close() {
    this.is_open_socket = false;
    clearInterval(this.heartbeatInterval);
    clearTimeout(this.reconnectTimeOut);
    if (this.socketTask) {
      this.socketTask.close();
    }
  }
}

export default WebsocketUtil;